package com.eqdd.yiqidian.ui.mine.space.fragment

import android.graphics.Bitmap
import android.os.Bundle
import android.support.v4.app.Fragment
import android.support.v7.widget.LinearLayoutManager
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.TextView
import com.bumptech.glide.Glide
import com.bumptech.glide.request.target.SimpleTarget
import com.bumptech.glide.request.transition.Transition
import com.eqdd.yiqidian.R
import com.eqdd.yiqidian.adapter.recycleadapter.BaseMultiItemQuickAdapter
import com.eqdd.yiqidian.adapter.recycleadapter.BaseViewHolder
import com.eqdd.yiqidian.adapter.recycleadapter.entity.MultiItemEntity
import com.eqdd.yiqidian.base.Config
import com.eqdd.yiqidian.bean.CompanyCultureBean
import com.eqdd.yiqidian.bean.ExcellentStaffBean
import com.eqdd.yiqidian.box.ItemDecoration.ITitleItemInterface
import com.eqdd.yiqidian.box.ItemDecoration.TitleItemDecoration
import com.eqdd.yiqidian.http.HttpConfig
import com.eqdd.yiqidian.http.HttpResult
import com.eqdd.yiqidian.http.JsonCallBack
import com.eqdd.yiqidian.kotlin.imgPathPreview
import com.eqdd.yiqidian.kotlin.listImagePreview
import com.eqdd.yiqidian.ui.companyspace.*
import com.eqdd.yiqidian.utils.ImageUtil
import com.lzy.okgo.OkGo
import com.lzy.okgo.model.Response
import io.reactivex.Observable
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.schedulers.Schedulers
import kotlinx.android.synthetic.main.fragment_company_space_detail.view.*
import org.jetbrains.anko.sdk25.coroutines.onClick
import org.jetbrains.anko.support.v4.startActivity
import org.jetbrains.anko.support.v4.toast
import java.util.*

/**
 * Created by jhj on 18-7-4.
 */
class CultureFragment : Fragment() {

    private var linearLayoutManager: LinearLayoutManager? = null

    override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
        val view = inflater.inflate(R.layout.fragment_company_space_detail, container, false)
        linearLayoutManager = LinearLayoutManager(activity)
        initData(view)
        return view
    }

    fun initData(view: View) {
        val userGuid = arguments?.getString(Config.GUID)
        val userCompanyId = arguments?.getInt("userCompanyId")
        val companyId = arguments?.getInt(Config.COMPANY_ID)

        if (userGuid == null || companyId == null || userCompanyId == null) {
            return
        }

        OkGo.post<HttpResult<CompanyCultureBean>>(HttpConfig.BASE_URL + HttpConfig.COMPANY_CULTURE_DETAIL)
                .params("userGuid", userGuid)
                .params("userGompanyId", userCompanyId)
                .params("companyId", companyId)
                .execute(object : JsonCallBack<HttpResult<CompanyCultureBean>>() {
                    override fun onSuccess(response: Response<HttpResult<CompanyCultureBean>>?) {
                        val result = response?.body()
                        if (result?.status == 200) {
                            val bean = result.items
                            formatData(bean, view)

                        } else {
                            toast(result?.msg ?: "获取信息失败")
                            activity?.finish()
                            return
                        }
                    }

                })
    }

    private fun formatData(bean: CompanyCultureBean?, view: View) {
        if (bean == null) return
        val list = arrayListOf<ItemBean>()
        Observable
                .create<List<ItemBean>> {
                    bean.comCoreValues?.forEach {
                        val itemBean = ItemBean()
                        itemBean.title = it.title
                        itemBean.image = it.imageUrl
                        itemBean.describe = it.describe
                        itemBean.tag = "核心价值观"
                        itemBean.type = 0
                        list.add(itemBean)
                    }
                    list.add(moreData(4, "核心价值观", bean.companyId))
                    bean.comActitivies?.forEach {
                        val itemBean = ItemBean()
                        itemBean.id = it.id
                        itemBean.title = it.title
                        itemBean.data = it.createTime
                        itemBean.tag = "领导活动"
                        itemBean.type = 1
                        list.add(itemBean)
                    }
                    list.add(moreData(4, "领导活动", bean.companyId))
                    bean.comEvent?.forEach {
                        val itemBean = ItemBean()
                        itemBean.id = it.id
                        itemBean.title = it.title
                        itemBean.data = it.createTime
                        itemBean.tag = "先进事迹"
                        itemBean.type = 2
                        list.add(itemBean)
                    }
                    list.add(moreData(4, "先进事迹", bean.companyId))
                    bean.comGoodStaff?.forEach {
                        val itemBean = ItemBean()
                        itemBean.id = it.id
                        itemBean.name = it.userName
                        itemBean.post = it.post
                        itemBean.image = it.headImage
                        itemBean.msg = it.msg
                        itemBean.tag = "优秀员工"
                        itemBean.type = 3
                        list.add(itemBean)
                    }
                    list.add(moreData(4, "优秀员工", bean.companyId))
                    it.onNext(list)
                }
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe {
                    val density: Float = activity?.resources?.displayMetrics?.density ?: 3f
                    val itemDecoration = TitleItemDecoration(activity, TitleItemDecoration.DECORATION_BOTTOM_COVER_TYPE)
                    itemDecoration
                            .setmTitleHeight(((45 * density).toInt()))
                            .setColorTitleBg(0xfff1f1f1.toInt())
                            .setColorTitleLine(0xff777777.toInt())
                            .setDatas(it)

                    view.recyclerView.layoutManager = linearLayoutManager
                    view.recyclerView.addItemDecoration(itemDecoration)
                    val adapter = ItemAdapter(it)
                    view.recyclerView.adapter = adapter
                }


    }

    private fun moreData(type: Int, tag: String, companyId: Int): ItemBean {
        val itemBean = ItemBean()
        itemBean.type = type
        itemBean.tag = tag
        itemBean.companyId = companyId
        return itemBean
    }


    inner class ItemAdapter(dataList: List<ItemBean>) : BaseMultiItemQuickAdapter<ItemBean, BaseViewHolder>(dataList) {
        init {
            addItemType(0, R.layout.list_item_160)
            addItemType(1, R.layout.list_item_163)
            addItemType(2, R.layout.list_item_163)
            addItemType(3, R.layout.list_item_153)
            addItemType(4, R.layout.list_item_165)
        }


        override fun convert(helper: BaseViewHolder?, item: ItemBean?) {
            when (helper?.itemViewType) {
                0 -> {
                    helper.getView<TextView>(R.id.tv_content_title).visibility = View.VISIBLE
                    helper.setText(R.id.tv_content_title, item?.title)
                    helper.setText(R.id.tv_content, item?.describe)
                    val imageView = helper.getView<ImageView>(R.id.iv_image)
                    if (item?.image.isNullOrBlank()) {
                        imageView.visibility = View.GONE
                    } else {
                        imageView.visibility = View.VISIBLE
                        item?.image?.let { activity?.listImagePreview(it, imageView) }
                    }
                }
                1,
                2 -> {
                    helper.setText(R.id.tv_content, item?.title)
                    helper.setText(R.id.tv_time, item?.data)
                }
                3 -> {
                    helper.setText(R.id.tv_name, String.format(Locale.CHINA, "姓名：%s", item?.name))
                    helper.setText(R.id.tv_post, String.format(Locale.CHINA, "职位：%s", item?.post))
                    helper.setText(R.id.tv_msg, String.format(Locale.CHINA, "简介：%s", item?.msg))
                    val imageView = helper.getView<ImageView>(R.id.iv_image)
                    if (item?.image?.isNotBlank() == true) {
                        imageView.visibility = View.VISIBLE
                        imageView.onClick {
                            activity?.imgPathPreview(item.image!!)
                        }
                        Glide.with(activity)
                                .asBitmap()
                                .apply(ImageUtil.optionsNormal)
                                .load(item.image)
                                .into(object : SimpleTarget<Bitmap>() {
                                    override fun onResourceReady(resource: Bitmap, transition: Transition<in Bitmap>) {
                                        val scale = resource.width.toDouble() / resource.height.toDouble()
                                        if (scale < 0.85 && scale > 0.65) {
                                            imageView.scaleType = ImageView.ScaleType.CENTER_CROP
                                        }
                                        imageView.setImageBitmap(resource)
                                    }
                                })
                    } else {
                        imageView.visibility = View.GONE
                    }


                }
                4 -> {
                    val textView = helper.getView<TextView>(R.id.tv_more)
                    textView.onClick {
                        if (item?.tag == "核心价值观") {
                            startActivity<CoreValueListActivity>(Config.COMPANY_ID to item.companyId, Config.TYPE to 1)
                        } else if (item?.tag == "领导活动") {
                            startActivity<LeaderMovableListActivity>(Config.COMPANY_ID to item.companyId, Config.TYPE to 1)
                        } else if (item?.tag == "先进事迹") {
                            startActivity<AdvancedEventListActivity>(Config.COMPANY_ID to item.companyId, Config.TYPE to 1)
                        } else if (item?.tag == "优秀员工") {
                            startActivity<ExcellentStaffListActivity>(Config.COMPANY_ID to item.companyId, Config.TYPE to 1)
                        }
                    }

                }
            }

            helper?.itemView?.onClick {
                when (item?.type) {
                    1 -> {
                        startActivity<LeaderMovableInfoActivity>(Config.ID to item.id)
                    }
                    2 -> {
                        startActivity<AdvancedEventInfoActivity>(Config.ID to item.id)
                    }
                    3 -> {
                        val excellentStaffBean = ExcellentStaffBean()
                        excellentStaffBean.id = item.id
                        excellentStaffBean.headImage = item.image
                        excellentStaffBean.msg = item.msg
                        excellentStaffBean.post = item.post
                        excellentStaffBean.userName = item.name
                        startActivity<ExcellentStaffInfoActivity>(Config.TYPE to 1, "data" to excellentStaffBean)
                    }

                }


            }

        }


    }

    class ItemBean : MultiItemEntity, ITitleItemInterface {

        var id: Int = -1
        var type: Int = -1
        var isTitle: Boolean = false
        var tag: String = ""


        var image: String? = null


        var title: String? = null
        var describe: String? = null

        var data: String? = null

        var name: String? = null
        var post: String? = null
        var msg: String? = null
        var companyId: Int = 0


        override fun getItemType(): Int {
            return type
        }

        override fun isShowTitle(): Boolean {
            return !isTitle
        }

        override fun getAlphaTag(): String {
            return tag
        }


    }
}